/**
 * 编程思路：使用传统阻塞式IO完成，每一个TCP连接，使用一个线程的方式
 */
package chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class BioChatServer {
    private static List<Socket> sockets=new ArrayList<>();
    public static void main(String[] args) throws Exception{
        int port=8000;
        ServerSocket serverSocket=new ServerSocket(8000);
        System.out.printf("服务器启动，使用： telnet localhost %d 登录.\n",port);
        while (true){
            Socket socket = serverSocket.accept();
            sockets.add(socket);
            new Thread(){
                @Override
                public void run() {
                    try {
                        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        socket.getOutputStream().write(("你是 "+Thread.currentThread().getName()+":\n").getBytes());
                        while (true){
                            String info=reader.readLine();
                            //广播
                            send(socket,Thread.currentThread().getName()+"说: "+ info);
                            if("bye".equals(info)){
                                socket.close();
                                sockets.remove(socket);
                                break;
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }.start();

        }
    }

    private static void send(Socket socket,String msg){
        try {
            for (int i = 0; i < sockets.size(); i++) {
                Socket sk = sockets.get(i);
                if(sk!=socket){
                    sk.getOutputStream().write((msg+"\n").getBytes());
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
